package com.txm.service;

import com.txm.qqcommon.Message;
import com.txm.qqcommon.Response;
import com.txm.qqcommon.User;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 用于用户的注册和登录
 * */
public class UserClientService {

    public static final User user = new User();
    private Socket socket;
    private Message message;

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public Message checkUser(String username, String password) {
        user.setUsername(username);
        user.setPassword(password);
        try {
            Socket socket = new Socket(GetHostName.getHost(), Integer.parseInt(GetHostName.getPort()));
            setSocket(socket);

            OutputStream outputStream = socket.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(new Response("/login", user));
//            objectOutputStream.writeObject(user);

//          等待接受返回值
            System.out.println("等待服务器验证。。。");
            InputStream inputStream = socket.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            Message message = (Message) objectInputStream.readObject();
            setMessage(message);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            if (e.toString().equals("java.net.ConnectException: Connection refused: connect")) {
                System.out.println("err:服务器未启动。");
            }else{
                System.out.println("err:" + e);
            }
        }
        return message;
    }
}
